﻿using Coldairarrow.Entity;
using Coldairarrow.Entity.BTB_StaffUsers;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.Goods;
using Coldairarrow.Entity.Purchasing;
using Coldairarrow.Entity.Statistics;
using Coldairarrow.IBusiness.BTB_StaffUsers;
using Coldairarrow.Util;
using Coldairarrow.Util.DbHelpers;
using EFCore.Sharding;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Coldairarrow.Business.BTB_StaffUsers
{
    public class BTB_UserVisitBusiness : BaseBusiness<BTB_UserVisit>, IBTB_UserVisitBusiness, ITransientDependency
    {
        public BTB_UserVisitBusiness(IDbAccessor db)
           : base(db)
        {
        }
        #region 统计

        /// <summary>
        /// 用户统计
        /// </summary>
        /// <returns></returns>
        public UserDTO IP()
        {
            UserDTO data = new UserDTO()
            {
                GetUserCount = GetUserCount(),
                GetUserBeforeCount = GetUserBeforeCount()
            };
            return data;
        }
        /// <summary>
        /// 访客统计
        /// </summary>
        /// <returns></returns>
        public VisitorDTO UV()
        {
            VisitorDTO data = new VisitorDTO()
            {
                GetUVCount = GetUVCount(),
                GetBeforeUVCount = GetBeforeUVCount()
            };
            return data;
        }
        /// <summary>
        /// 销量统计
        /// </summary>
        /// <returns></returns>
        public SalesDTO Sales()
        {
            SalesDTO data = new SalesDTO()
            {
                GetSales = GetSales(),
                GetBeforeSales = GetBeforeSales()
            };
            return data;
        }
        /// <summary>
        /// 销量额统计
        /// </summary>
        /// <returns></returns>
        public SalesVolumeDTO SalesVolume()
        {
            SalesVolumeDTO data = new SalesVolumeDTO()
            {
                SalesVolume = SalesVolumes(),
                SalesBeforeVolume = SalesBeforeVolume()
            };
            return data;
        }
        /// <summary>
        /// 订单量统计
        /// </summary>
        /// <returns></returns>
        public ClinchOrderDTO GetOrder()
        {
            ClinchOrderDTO data = new ClinchOrderDTO()
            {
                ClinchOrder = clinchOrder(),
                ClinchBeforeOrder = clinchBeforeOrder()
            };
            return data;
        }
        /// <summary>
        /// 代办事项
        /// </summary>
        /// <returns></returns>
        public TodoDTO GetTodo()
        {
            TodoDTO data = new TodoDTO()
            {
                TodoOrder = TodoOrder(),
                TodoInvoice = TodoInvoice(),
                TodoComments = TodoComments(),
                TodoWarning = TodoWarning()
            };
            return data;
        }
        /// <summary>
        /// 订单通知
        /// </summary>
        /// <returns></returns>
        public int Getnotification()
        {
            return Db.GetIQueryable<Order_Master>().Where(q => q.OrderState == 1).Count();
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task AddDataAsync(BTB_UserVisit data)
        {
            await InsertAsync(data);
        }
        /// <summary>
        /// 前台插入ip
        /// </summary>
        /// <returns></returns>
        public async Task GetIP()
        {
            BTB_UserVisit data = new BTB_UserVisit()
            {
                id = GuidHelper.GenerateKey(),
                CreateTime = DateTime.Now,
                VisitIP = IpHelper.GetLocalIp()
            };
            await InsertAsync(data);
        }
        /// <summary>
        /// 支付方式对应支付金额
        /// </summary>
        /// <returns></returns>
        public async Task<PayDTO> GetPayStatse(PayStatseDTO input)
        {
            //品牌
            if (input.Start.HasValue && input.End.HasValue)
            {
                PayDTO data = new PayDTO()
                {
                    WechatMoney = Db.GetIQueryable<Order_Master>(true).Where(k => (k.CreateTime >= input.Start && k.CreateTime <= input.End) && (k.PayState == 2 || k.PayState == 3)).Sum(a => a.TotalPrice),
                    aliyun = Db.GetIQueryable<Order_Master>(true).Where(k => k.CreateTime >= input.Start && k.CreateTime <= input.End && k.PayState == 1).Sum(a => a.TotalPrice),
                };
                return data;
            }
            else
            {
                DateTime? start = Convert.ToDateTime( DateTime.Now.ToString("yyyy-MM-dd"));
                DateTime? end = Convert.ToDateTime(DateTime.Now.AddDays(+1).ToString("yyyy-MM-dd"));
                PayDTO data = new PayDTO()
                {
                    WechatMoney = Db.GetIQueryable<Order_Master>(true).Where(k => (k.CreateTime >= start && k.CreateTime <= end) && (k.PayState == 2 || k.PayState == 3)).Sum(a => a.TotalPrice),
                    aliyun = Db.GetIQueryable<Order_Master>(true).Where(k => k.CreateTime >= start && k.CreateTime <= end && k.PayState == 1).Sum(a => a.TotalPrice),
                };
                return data;
            }
        }

        #region 获取销售数量统计数据
        /// <summary>
        /// 获取销售数量统计数据
        /// </summary>
        /// <param name="Year">年</param>
        /// <returns></returns>
        public List<LinChartStatistical> GetDayGoodsNumber(int Year)
        {
            DateTime Date = Convert.ToDateTime(Year + "-01-01");

            StringBuilder strSql = new StringBuilder();
            for (int i = 0; i < 12; i++)
            {
                if (i > 0)
                {
                    strSql.Append(" union select " + i + 1 + " as ID,'" + Date.AddMonths(i).ToString("MM月") + "' as DTName,SUM(Totalnum) as Account  from Order_Master where OrderState in(1,2,3,4) and CreateTime>='" + Date.AddMonths(i).ToString("yyyy-MM-dd") + " 00:00:00.000' and CreateTime<='" + Date.AddMonths(i + 1).AddDays(-1).ToString("yyyy-MM-dd") + " 23:59:59.999' ");
                }
                else
                {
                    strSql.Append(" select " + i + 1 + " as ID,'" + Date.AddMonths(i).ToString("MM月") + "' as DTName,SUM(Totalnum) as Account  from Order_Master where OrderState in(1,2,3,4) and CreateTime>='" + Date.AddMonths(i).ToString("yyyy-MM-dd") + " 00:00:00.000' and CreateTime<='" + Date.AddMonths(i + 1).AddDays(-1).ToString("yyyy-MM-dd") + " 23:59:59.999' ");
                }
            }
            List<LinChartStatistical> List = new List<LinChartStatistical>();
            if (string.IsNullOrEmpty(strSql.ToString()))
            {
                return null;
            }
            DataSet ds = DbHelperSQL.Query(strSql.ToString());
            DataTable dt = ds.Tables[0];
            if (dt.Rows.Count > 0)
            {
                LinChartStatistical model = new LinChartStatistical();
                for (int n = 0; n < dt.Rows.Count; n++)
                {
                    model = new LinChartStatistical();
                    if (dt.Rows[n]["ID"].ToString() != "")
                    {
                        model.ID = int.Parse(dt.Rows[n]["ID"].ToString());
                    }
                    if (dt.Rows[n]["DTName"].ToString() != "")
                    {
                        model.DTName = dt.Rows[n]["DTName"].ToString();
                    }
                    if (dt.Rows[n]["Account"].ToString() != "")
                    {
                        model.Account = Convert.ToInt32(dt.Rows[n]["Account"].ToString());
                    }
                    List.Add(model);
                }
            }
            return List;
        }
        #endregion


        #region 获取销售金额统计数据
        /// <summary>
        /// 获取销售金额统计数据
        /// </summary>
        /// <param name="Year">年</param>
        /// <returns></returns>
        public List<LinChartStatistical> GetDayOrderPrince(int Year)
        {

            DateTime Date = Convert.ToDateTime(Year + "-01-01");


            StringBuilder strSql = new StringBuilder();
            for (int i = 0; i < 12; i++)
            {
                if (i > 0)
                {
                    strSql.Append(" union select " + i + 1 + " as ID,'" + Date.AddMonths(i).ToString("MM月") + "' as DTName,CONVERT(decimal(18,2),SUM(TotalPrice)) as Amount  from Order_Master where OrderState in(1,2,3,4) and CreateTime>='" + Date.AddMonths(i).ToString("yyyy-MM-dd") + " 00:00:00.000' and CreateTime<='" + Date.AddMonths(i + 1).AddDays(-1).ToString("yyyy-MM-dd") + " 23:59:59.999' ");
                }
                else
                {
                    strSql.Append(" select " + i + 1 + " as ID,'" + Date.AddMonths(i).ToString("MM月") + "' as DTName,CONVERT(decimal(18,2),SUM(TotalPrice)) as Amount  from Order_Master where OrderState in(1,2,3,4) and CreateTime>='" + Date.AddMonths(i).ToString("yyyy-MM-dd") + " 00:00:00.000' and CreateTime<='" + Date.AddMonths(i + 1).AddDays(-1).ToString("yyyy-MM-dd") + " 23:59:59.999' ");
                }
            }
            List<LinChartStatistical> List = new List<LinChartStatistical>();
            if (string.IsNullOrEmpty(strSql.ToString()))
            {
                return null;
            }
            DataSet ds = DbHelperSQL.Query(strSql.ToString());
            DataTable dt = ds.Tables[0];
            if (dt.Rows.Count > 0)
            {
                LinChartStatistical model = new LinChartStatistical();
                for (int n = 0; n < dt.Rows.Count; n++)
                {
                    model = new LinChartStatistical();
                    if (dt.Rows[n]["ID"].ToString() != "")
                    {
                        model.ID = int.Parse(dt.Rows[n]["ID"].ToString());
                    }
                    if (dt.Rows[n]["DTName"].ToString() != "")
                    {
                        model.DTName = dt.Rows[n]["DTName"].ToString();
                    }
                    if (dt.Rows[n]["Amount"].ToString() != "")
                    {
                        model.Amount = Convert.ToDecimal(dt.Rows[n]["Amount"].ToString());
                    }
                    List.Add(model);
                }
            }
            return List;
        }
        #endregion

        #endregion

        #region 方法

        /// <summary>
        ///总用户统计
        /// </summary>
        /// <returns></returns>
        public int GetUserCount()
        {
            return Db.GetIQueryable<BTB_StaffUser>(true).Count();
        }
        /// <summary>
        /// 仅七天用户统计
        /// </summary>
        /// <returns></returns>
        public int GetUserBeforeCount()
        {
            var GetNowDate = DateTime.Now;
            var GetBeforDate = DateTime.Now.AddDays(-7);
            return Db.GetIQueryable<BTB_StaffUser>(true).Where(x => x.CreateTime >= GetBeforDate && x.CreateTime <= GetNowDate).Count();
        }
        /// <summary>
        /// 访客统计
        /// </summary>
        /// <returns></returns>
        public int GetUVCount()
        {
            return Db.GetIQueryable<BTB_UserVisit>(true).Count();
        }
        /// <summary>
        /// 仅七天访客统计
        /// </summary>
        /// <returns></returns>
        public int GetBeforeUVCount()
        {
            var GetNowDate = DateTime.Now;
            var GetBeforDate = DateTime.Now.AddDays(-7);
            return Db.GetIQueryable<BTB_UserVisit>(true).Where(x => x.CreateTime >= GetBeforDate && x.CreateTime <= GetNowDate).Count();
        }
        /// <summary>
        /// 总访客统计
        /// </summary>
        /// <returns></returns>
        public int GetPVCount()
        {
            return Db.GetIQueryable<BTB_UserVisit>(true).Select(x => x.VisitIP).Distinct().Count();
        }
        /// <summary>
        /// 仅七天销量
        /// </summary>
        /// <returns></returns>
        public int? GetBeforeSales()
        {
            var GetNowDate = DateTime.Now;
            var GetBeforDate = DateTime.Now.AddDays(-2);
            return Db.GetIQueryable<Order_Master>()
                 .Where(x => x.CreateTime >= GetBeforDate && x.CreateTime <= GetNowDate && x.OrderState == 2 || x.OrderState == 1 || x.OrderState == 3 || x.OrderState == 4)
                 .Sum(a => a.Totalnum);
        }
        /// <summary>
        /// 总销量
        /// </summary>
        /// <returns></returns>
        public int? GetSales()
        {
            return Db.GetIQueryable<Order_Master>(true).Where(x => x.OrderState == 2 || x.OrderState == 1 || x.OrderState == 3 || x.OrderState == 4).Sum(a => a.Totalnum);
        }
        /// <summary>
        /// 仅七天销售额
        /// </summary>
        /// <returns></returns>
        public decimal? SalesBeforeVolume()
        {
            DateTime? GetNowDate = DateTime.Now;
            DateTime? GetBeforDate = DateTime.Now.AddDays(-7);
            return Db.GetIQueryable<Order_Master>(true).Where(x => x.CreateTime >= GetBeforDate && x.CreateTime <= GetNowDate && x.OrderState == 2 || x.OrderState == 1 || x.OrderState == 3 || x.OrderState == 4).Sum(a => a.TotalPrice);
        }
        public decimal? SalesVolumes()
        {
            return Db.GetIQueryable<Order_Master>(true).Where(x => x.OrderState == 2 || x.OrderState == 1 || x.OrderState == 3 || x.OrderState == 4).Sum(a => a.TotalPrice);
        }


        /// <summary>
        /// 仅七天订单量
        /// </summary>
        /// <returns></returns>
        public int? clinchOrder()
        {
            var GetNowDate = DateTime.Now;
            var GetBeforDate = DateTime.Now.AddDays(-2);
            return Db.GetIQueryable<Order_Master>()
                 .Where(x => x.CreateTime >= GetBeforDate && x.CreateTime <= GetNowDate).Count();
        }
        /// <summary>
        /// 总订单量
        /// </summary>
        /// <returns></returns>
        public int? clinchBeforeOrder()
        {
            return Db.GetIQueryable<Order_Master>(true).Count();
        }

        public int? TodoOrder()
        {
            return Db.GetIQueryable<Order_Master>().Where(q => q.OrderState == 1).Count();
        }
        public int? TodoInvoice()
        {
            return Db.GetIQueryable<Invoice_Info>().Where(q => q.state == 0).Count();
        }
        public int? TodoComments()
        {
            return Db.GetIQueryable<BTB_Comment>().Where(q => q.State == 0).Count();
        }
        public int? TodoWarning()
        {
            return Db.GetIQueryable<BTB_GoodsSpecificationsItem>().Where(q => q.Inventory < q.stock).Count();
        }

        #endregion
    }

}
